package com.sumainfor.pc.gmio.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sumainfor.common.config.RedisUtils;
import com.sumainfor.common.util.*;
import org.apache.kafka.common.security.oauthbearer.internals.OAuthBearerClientInitialResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhoucong
 * @ClassName IntelligentService
 * @date 2019/12/14 13:55
 * @description: TODO
 */
@Service
public class IntelligentService implements Serializable {

    @Autowired
    RedisUtils redisUtils;

    /**
     * 发送智能设备密码
     * @param params
     * @return
     */
    public JsonResult getIntelligentDoor(Map<String,Object> params){
        JsonResult result = new JsonResult();

//        phone
//        identifierList

        //智能设备的数据
        List<Map<String,Object>> identifierList=(List<Map<String,Object>>)params.get("identifierList");

        for (Map<String,Object> InteMap:identifierList){
            //Intelligent 0.蜂电   1.大华   2.科技侠   3.果加
            if (InteMap.get("Intelligent").toString().equals("2")){
                String DeviceLockToken=redisUtils.get("DeviceLockToken");
                //如果获取不到就重新登录
                if (DeviceLockToken==null){
                    Map<String,Object> tokenMap=new HashMap<String, Object>();
                    params.put("client_id", InteDeviceLockConfig.CLIENT_ID);
                    params.put("client_secret",InteDeviceLockConfig.CLIENT_SECRET);
                    params.put("grant_type",InteDeviceLockConfig.GRANT_TYPE_PASSWORD);
                    params.put("username",InteDeviceLockConfig.USERNAME);
                    params.put("password",InteDeviceLockConfig.PASSWORD);
                    params.put("redirect_uri",InteDeviceLockConfig.REDIRECT_URL);
                    tokenMap= InteDeviceLockUtil.oauth2Token(params);
                    if (tokenMap.get("access_token")!=null){
                        DeviceLockToken=tokenMap.get("access_token").toString();
                        //token存到redis中
                        redisUtils.set("DeviceLockToken",DeviceLockToken,Long.valueOf(tokenMap.get("expires_in").toString()));
                    }else{
                        return result.putFailed("token获取失败");
                    }
                }


//                Map<String,Object> verMap = new HashMap<>();
//                verMap.put("clientId", InteDeviceLockConfig.CLIENT_ID);//应用编号
//                verMap.put("accessToken",DeviceLockToken);//访问令牌
//                verMap.put("lockId",InteMap.get("Identifier"));//智能设备编号
//                verMap.put("date",InteDeviceLockUtil.getTimeSign());//当前时间
//                Map<String,Object> versionMap = InteDeviceLockUtil.getKeyboardPwdVersion(verMap);//获取锁的键盘版本号



                Map<String,Object> sendMap = new HashMap<>();
                sendMap.put("clientId", InteDeviceLockConfig.CLIENT_ID);//应用编号
                sendMap.put("accessToken",DeviceLockToken);//访问令牌
                sendMap.put("lockId",InteMap.get("Identifier"));//智能设备编号
                sendMap.put("receiverUsername",params.get("phone"));//接收方用户名
                sendMap.put("keyName","科技侠");//钥匙名
                sendMap.put("startDate",InteDeviceLockUtil.getTimeSign(DateUtils.format(DateUtils.addDateMonths( DateUtils.stringToDate(params.get("StartTime").toString(),"yyyy-MM-dd"),0))+InteDeviceLockConfig.LOCK_TIME_START,"yyyy-MM-dd HH:mm:ss"));
                sendMap.put("endDate",InteDeviceLockUtil.getTimeSign(DateUtils.format(DateUtils.addDateMonths( DateUtils.stringToDate(params.get("EndTime").toString(),"yyyy-MM-dd"),0))+InteDeviceLockConfig.LOCK_TIME_END,"yyyy-MM-dd HH:mm:ss"));
                sendMap.put("remarks","发送钥匙");//备注,留言
                sendMap.put("remoteEnable",2);//是否支持远程开锁 1是 2 否
                sendMap.put("date",InteDeviceLockUtil.getTimeSign());//当前时间(毫秒数)
                Map<String,Object> mapResult=InteDeviceLockUtil.keySend(sendMap);
                System.out.println("钥匙返回的参数:"+mapResult);
                System.out.println("InteMap1:"+InteMap);
                if (mapResult.get("errcode")!=null && mapResult.get("errcode").toString().equals("0")){
                    InteMap.put("CodeId",mapResult.get("keyId"));//密码ID
                    InteMap.put("Operator",ContextUtils.getUserId());
                }else{
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return  result.putFailed(mapResult.get("errmsg").toString());
                }

            }else if(InteMap.get("Intelligent").toString().equals("3")){//果加
                String GuoJiaToken=redisUtils.get("GuoJiaToken");
                //如果获取不到就重新登录
                if (GuoJiaToken==null){
                    Map<String,Object> guoJiaMap=new HashMap<String, Object>();
                    guoJiaMap.put("s_id", InteGuoJiaUtil.getSid());
                    guoJiaMap.put("version","1");
                    com.alibaba.fastjson.JSONObject bodyJson=new com.alibaba.fastjson.JSONObject();
                    //key
                    DESEncrypt desPlus2 = new DESEncrypt(InteGuoJiaConfig.DES_KEY);
                    //密码
                    bodyJson.put("account",InteGuoJiaConfig.ACCOUNT);
                    bodyJson.put("password",desPlus2.encrypt(InteGuoJiaConfig.PASSWORD));
                    guoJiaMap= InteGuoJiaUtil.login(guoJiaMap,bodyJson);
                    //返回的token数据
                    Map<String,Object>dataMap=(Map<String,Object>)guoJiaMap.get("data");
                    if (guoJiaMap.get("rlt_code").toString().equals("HH0000")){//HH0000 、成功
                        GuoJiaToken=dataMap.get("access_token").toString();
                        //token存到redis中
                        redisUtils.set("GuoJiaToken",GuoJiaToken,Long.valueOf(dataMap.get("expires_second").toString()));
                    }else{
                        return result.putFailed("token获取失败");
                    }
                }
                /*发送果加的门锁钥匙*/
                Map<String,Object> headParams=new HashMap<String, Object>();
                headParams.put("s_id",InteGuoJiaUtil.getSid());
                headParams.put("version","1");
                headParams.put("access_token",GuoJiaToken);
                JSONObject bodyJson=new JSONObject();
                bodyJson.put("operate_pwd_auth","N");//是否允许操作密码 Y 允许 N 不允许
                bodyJson.put("set_custom_pwd","N");//是否允许设置自定义密码 Y 允许 N 不允许智能是否允许设置自定义密码 Y 允许 N 不允许
                bodyJson.put("lock_no",InteMap.get("Identifier"));//智能门锁的设备编号
                bodyJson.put("mobile",params.get("phone"));//用户手机号
                bodyJson.put("auth_time_start",InteDeviceLockUtil.getTimeSign(DateUtils.format(DateUtils.addDateMonths( DateUtils.stringToDate(params.get("StartTime").toString(),"yyyy-MM-dd"),0))+InteDeviceLockConfig.LOCK_TIME_START,"yyyy-MM-dd HH:mm:ss"));
                bodyJson.put("auth_time_end",InteDeviceLockUtil.getTimeSign(DateUtils.format(DateUtils.addDateMonths( DateUtils.stringToDate(params.get("EndTime").toString(),"yyyy-MM-dd"),0))+InteDeviceLockConfig.LOCK_TIME_END,"yyyy-MM-dd HH:mm:ss"));
                Map<String,Object> guoJiaResult=InteGuoJiaUtil.lockAuth(headParams,bodyJson);
                if (guoJiaResult.get("rlt_code") !=null && guoJiaResult.get("rlt_code").toString().equals("HH0000")){//HH0000 、成功
                    InteMap.put("CodeId",InteMap.get("Identifier"));//钥匙的编码就存智能设备编码
                    InteMap.put("Code",InteMap.get("TenMode"));//果加的密码就存租客手机号
                }else{
                    return result.putFailed(guoJiaResult.get("rlt_msg").toString());
                }
            }
        }
return result.put(identifierList);
    }


}
